<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <el-row :gutter="20">
        <el-col :span="7">
          <el-input placeholder="请输入内容" v-model="userData.query">
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" plain @click="getAll" size="mini"
            >全部</el-button
          >
          <el-button
            type="primary"
            plain
            @click="dialogVisible = true"
            size="mini"
            >添加用户
          </el-button>
        </el-col>
      </el-row>
      <!-- 用户列表 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column type="index" width="50" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名" width="100">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="电话" width="110">
        </el-table-column>
        <el-table-column prop="role_name" label="权限" width="100">
        </el-table-column>
        <el-table-column prop="mg_state" label="状态" width="100">
          <template v-slot="slotProps">
            <el-switch
              v-model="slotProps.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="slotProps">
            <el-tooltip
              class="item"
              effect="dark"
              content="修改"
              placement="top"
            >
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="onUpdataUser(slotProps.row)"
              ></el-button
            ></el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="onDeleteUser(slotProps.row.id)"
              ></el-button
            ></el-tooltip>
            <el-tooltip
              class="item"
              effect="dark"
              content="更改权限"
              placement="top"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="editRole(slotProps.row)"
              ></el-button
            ></el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userData.pagenum"
        :page-sizes="[1, 2, 5, 8]"
        :page-size="userData.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totol"
      >
      </el-pagination>
    </el-card>
    <!-- 添加用户的对话框 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%">
      <!-- 主体区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addForm.password"
            show-password
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email" type="email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
        <el-button @click="addFormRest">重置</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog
      title="修改用户信息"
      :visible.sync="updataUsers"
      width="50%"
      @close="udaptaClose"
    >
      <!-- 主体区域 -->
      <el-form
        :model="updataForm"
        status-icon
        :rules="addFormRules"
        ref="updataForm"
        label-width="70px"
      >
        <el-form-item label="用户名">
          <el-input v-model="updataForm.username" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="updataForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="updataForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- footer区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="updataUsers = false">取 消</el-button>
        <el-button type="primary" @click="updataUserGit">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="提示" :visible.sync="popleFen" width="50%" @close="closePople">
      <div>名称：{{ userInfo.username }}</div>
      <div>权限：{{ userInfo.role_name }}</div>
      <el-select v-model="selectId" placeholder="请选择">
        <el-option
          v-for="item in RoleList"
          :key="item.id"
          :label="item.roleName"
          :value="item.id"
        >
        </el-option>
      </el-select>

      <span slot="footer" class="dialog-footer">
        <el-button @click="popleFen = false">取 消</el-button>
        <el-button type="primary" @click="editUserif">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'User',
  data() {
    return {
      userData: {
        query: '',
        pagenum: 1,
        pagesize: 2,
      },
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: '',
      },
      updataForm: {
        id: '',
        username: '',
        email: '',
        mobile: '',
      },
      userList: [],
      totol: 0,
      dialogVisible: false,
      updataUsers: false,
      popleFen: false,

      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 18,
            message: '长度在 3 到 18 个字符',
            trigger: 'blur',
          },
        ],
        password: [
          { required: true, message: '请输入密码名', trigger: 'blur' },
          {
            min: 3,
            max: 18,
            message: '长度在 3 到 18 个字符',
            trigger: 'blur',
          },
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change'],
          },
        ],
        mobile: [{ required: true, message: '请输入邮箱', trigger: 'blur' }],
      },
      userInfo: {},
      RoleList: [],
      selectId: '',
    }
  },
  created() {
    this.getUsers()
  },

  methods: {
    async getUsers() {
      const { data: res } = await this.$http.get('users', {
        params: this.userData,
      })
      if (res.meta.status !== 200)
        return this.$message.error('获取用户列表失败')
      this.userList = res.data.users
      // console.log(res)
      this.totol = res.data.total
    },
    handleSizeChange(newPageSize) {
      this.userData.pagesize = newPageSize
      // 当数据发生改变，发送一次请求
      this.getUsers()
    },
    handleCurrentChange(newPageNum) {
      this.userData.pagenum = newPageNum
      this.getUsers()
    },
    getAll() {
      this.userData.query = ''
      this.getUsers()
    },
    addFormRest() {
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error('请正确填写数据表')
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error('创建用户失败')
        this.$message.success('创建用户成功')
        this.dialogVisible = false
        this.getUsers()
      })
    },
    onUpdataUser(data) {
      // console.log(data)
      this.updataUsers = true
      this.updataForm.username = data.username
      this.updataForm.email = data.email
      this.updataForm.mobile = data.mobile
      this.updataForm.id = data.id
    },
    udaptaClose() {
      this.$refs.updataForm.resetFields()
    },
    updataUserGit() {
      this.$refs.updataForm.validate(async (valid) => {
        if (!valid) return this.$message.error('请正确填写数据表')
        // console.log(this.updataForm.id)
        const { data: res } = await this.$http.put(
          'users/' + this.updataForm.id,
          {
            email: this.updataForm.email,
            mobile: this.updataForm.mobile,
          }
        )
        if (res.meta.status !== 200) return this.$message.error('更新用户失败')
        this.$message.success('更新用户成功')
        this.updataUsers = false
        this.getUsers()
      })
    },
    async onDeleteUser(id) {
      const resFirm = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      if (resFirm !== 'confirm') {
        // console.log(resFirm)
        return this.$message.info('已取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      // console.log(res)
      if (res.meta.status !== 200) return this.$message.error('删除用户失败！')
      this.$message.success('删除用户成功！')
      this.getUsers()
    },
    async editRole(row) {
      this.popleFen = true
      const { data: res } = await this.$http.get('roles')
      this.RoleList = res.data
      this.userInfo = row
    },
   async editUserif(){
      if(!this.selectId) return this.$message.error('请选择用户权限')
      const {data:res} =await this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectId})
      if (res.meta.status !== 200) return this.$message.error('更新失败！')
      this.$message.success('更新成功！')
      this.getUsers()
      this.popleFen = false
    },
    closePople(){
      this.selectId=''
    }
  },
}
</script>

<style lang="less" scoped>
.box-card {
  margin: 20px 10px 0px 10px;
}
.el-row {
  padding-bottom: 10px;
}
</style>